#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QHostAddress>
#include <QMessageBox>
#include <QRegularExpression>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

bool MainWindow::is_valid_ip(const QString &ipStr) {
    QRegularExpression ipRegex(R"(^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$)");
    return ipRegex.match(ipStr).hasMatch();
}


void MainWindow::on_pushButton_clicked() {
    QString ipStr = ui->lineEdit_ipaddr->text().trimmed();
    QString portStr = ui->lineEdit_port->text().trimmed();

    QRegularExpression re("^(6553[0-5]|655[0-2]\\d|65[0-4]\\d{2}|6[0-4]\\d{3}|[1-5]\\d{4}|[1-9]\\d{0,3}|0)$");
    QRegularExpressionMatch match = re.match(portStr);

    if (!is_valid_ip(ipStr)) {
        QMessageBox::warning(this, "错误", "请输入合法的IPv4地址");
        return;
    }

    if (!match.hasMatch()) {
        QMessageBox::warning(this, "错误", "请输入有效的UDP端口号 (0-65535)");
        return;
    }

    int port = portStr.toInt();

    if (udpSocket) {
        udpSocket->close();
        delete udpSocket;
        udpSocket = nullptr;
    }

    udpSocket = new QUdpSocket(this);
    if (!udpSocket->bind(QHostAddress(ipStr), port)) {
        QMessageBox::critical(this, "错误", "绑定端口失败");
        return;
    }

    connect(udpSocket, &QUdpSocket::readyRead, this, &MainWindow::onReadyRead);

    int threadCount = 12;
    for (int i = 0; i < threadCount; ++i) {
        UdpWorkerThread* workerThread = new UdpWorkerThread();
        connect(workerThread->getWorker(), &UdpWorker::dataProcessed, this, &MainWindow::onDataProcessed);
        workerThread->start();
        workers.append(workerThread);
    }

    qDebug() << "开始监听 UDP 数据：" << ipStr << ":" << port;
    ui->label_status->setText(QString("开始监听 UDP 数据"));
}

void MainWindow::on_pushButton_stop_clicked() {
    if (udpSocket) {
        udpSocket->close();
        delete udpSocket;
        udpSocket = nullptr;
    }

    for (auto thread : workers) {
        thread->stop();
        delete thread;
    }
    workers.clear();
    ui->label_status->setText(QString(""));
}

void MainWindow::onReadyRead() {
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        udpSocket->readDatagram(datagram.data(), datagram.size());

        static int index = 0;
        UdpWorker* worker = workers[index++ % workers.size()]->getWorker();
        QMetaObject::invokeMethod(worker, "onNewData", Qt::QueuedConnection, Q_ARG(QByteArray, datagram));
    }
}

void MainWindow::onDataProcessed(qint64 size, qint64 time) {
   ui->label_status->setText(QString("收到 %1 字节数据，处理耗时 %2 毫秒").arg(size).arg(time));
  //  ui->l
}


void MainWindow::on_pushButton_exit_clicked()
{
    QApplication::quit();
}
